import Youdao from './translate';
import * as flatCache from 'flat-cache';
import * as path from 'path';
import * as changeCase from 'change-case';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { getFirstPY } = require('getpinyin');

export const cache = flatCache.load('default', path.resolve('./cache'));

export const jenkins = new Youdao({
  appSecret: 'dk8yEhpujV5Hnq7iylD9GbygkUXvR2lT',
  appKey: '0c08146320edd374',
});

function engToResult(eng: string) {
  // 输入验证和清理
  if (!eng || typeof eng !== 'string') {
    eng = '';
  }

  // 清理输入，移除特殊字符
  const cleanEng =
    eng
      .replace(/["'`$()\[\]{}<>|\\\/]/g, '') // 移除各种引号和特殊字符
      .replace(/[^\w\s_]/g, '') // 移除非字母数字下划线和空格的字符
      .replace(/\s+/g, '_') // 将连续空格替换为下划线
      .replace(/_+/g, '_') // 将连续下划线合并为单个
      .replace(/^_|_$/g, '') // 移除开头和结尾的下划线
      .trim() || ''; // 如果结果为空，使用默认值

  const camelCase = changeCase.camelCase(cleanEng);
  return {
    text: cleanEng,
    paramCase: changeCase.paramCase(cleanEng),
    camelCase,
    upperCaseFirst:
      camelCase.slice(0, 1).toUpperCase() +
      camelCase.slice(1, camelCase.length),
  };
}

export const checkHasChinese = function (text: string) {
  const res = text.match(/[^\x00-\x80]/g);
  return res && res.length > 0;
};

export async function chineseToEnglish(title: string, retry?: number) {
  // 输入验证
  if (!title || typeof title !== 'string') {
    return engToResult('');
  }

  // 清理输入字符串，移除前后空格
  const cleanTitle = title.trim();

  // 判断是否是中文
  if (!checkHasChinese(cleanTitle)) {
    return engToResult(cleanTitle);
  }

  const titleCache = cache.getKey(cleanTitle);
  // 解决之前缓存存的是string的问题
  if (titleCache) {
    return typeof titleCache === 'string'
      ? engToResult(titleCache)
      : titleCache;
  }
  const res: any = await jenkins.translate(cleanTitle, {
    from: 'zh',
    to: 'en',
  });
  const { errorCode, translation } = res;
  if (errorCode === '0' && translation?.length > 0 && translation[0]) {
    let eng = translation[0]
      .toLowerCase()
      .split(' ')
      .join('_')
      .replace(/["'`$()\[\]{}<>|\\\/]/g, '') // 移除各种引号和特殊字符
      .replace(/[^\w\s_]/g, '') // 移除非字母数字下划线和空格的字符
      .replace(/\s+/g, '_') // 将连续空格替换为下划线
      .replace(/_+/g, '_') // 将连续下划线合并为单个
      .replace(/^_|_$/g, ''); // 移除开头和结尾的下划线

    // 如果处理后为空字符串，使用拼音
    if (!eng || eng.trim() === '') {
      eng = getFirstPY(cleanTitle);
    }

    // 如果仍然包含中文，使用拼音
    if (checkHasChinese(eng)) {
      eng = getFirstPY(eng);
    }

    // 最终验证，确保结果有效
    if (!eng || eng.trim() === '') {
      eng = '';
    }

    const result = engToResult(eng);
    cache.setKey(cleanTitle, result);
    return result;
  } else {
    if (errorCode === '411' && (retry || 0) < 5) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(chineseToEnglish(cleanTitle, (retry || 0) + 1));
        }, 1000 * (retry || 0) + 1000);
      });
    }
  }

  // 翻译失败时，尝试使用拼音
  const fallbackPy = getFirstPY(cleanTitle);
  if (fallbackPy && fallbackPy.trim() !== '') {
    return engToResult(fallbackPy);
  }

  // 最终回退到清理后的标题或默认值
  return engToResult(cleanTitle || '');
}
